package com.woorigil.social.parser.wemakeprice;

import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;

import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.woorigil.social.DateUtils;
import com.woorigil.social.DiscountUtils;
import com.woorigil.social.domain.ProviderCode;
import com.woorigil.social.domain.deal.Deal;
import com.woorigil.social.domain.deal.DealListDocument;
import com.woorigil.social.domain.deal.ManageStatus;
import com.woorigil.social.parser.CategoryMapper;
import com.woorigil.social.parser.LocalCategoryUtils;
import com.woorigil.social.parser.XmlParser;

@Component (value="wemakepriceXmlParser")
public class WemakepriceXmlParser extends XmlParser {
	private static Logger log = LoggerFactory.getLogger(WemakepriceXmlParser.class);
	
	public static Map<String, WemakeExtraDeal> extraDeals;

	@Value("${wemakeprice.deal.path}") 
	String dealPath;
	
	@Override
	public String getCharsetName() {
		return "UTF-8";
	}

	@Override
	public ProviderCode getProviderCode() {
		return ProviderCode.WM;
	}
	
	@Override
	public String getSourcePath() {
		return dealPath;
	}

	@Override
	public DealListDocument parse(Reader reader) throws ValidityException, ParsingException, IOException {
		if (extraDeals == null) {
			extraDeals = new HashMap<String, WemakeExtraDeal>();
		}
		
		extraDeals.putAll(new LocalSiteParser().parse());
		extraDeals.putAll(new CultureSiteParser().parse());
		extraDeals.putAll(new TourSiteParser().parse());
		extraDeals.putAll(new ShoppingSiteParser().parse());

		Builder builder = new Builder();
		Document doc = builder.build(reader);
		Element root = doc.getRootElement();
		
		DealListDocument dealListDocument = new DealListDocument();
		dealListDocument.setSourceProvider(getValue(root.getFirstChildElement("name")));
		dealListDocument.setVersion(getValue(root.getFirstChildElement("doc_ver")));
		dealListDocument.setHomepage(getValue(root.getFirstChildElement("url")));
		dealListDocument.setLogo(getValue(root.getFirstChildElement("logo_image")));
		
		Element dealsEle = root.getFirstChildElement("deals");
		Elements dealsEles = dealsEle.getChildElements();
		for (int i = 0; i < dealsEles.size(); i++) {
			try {
				Element dealEl = dealsEles.get(i);
	
				Deal deal = new Deal();
				deal.setProviderCode(getProviderCode());
				deal.setMetaId(getValue(dealEl.getFirstChildElement("meta_id")));
				deal.setCategory(getValue(dealEl.getFirstChildElement("category")));
				deal.setSection1(getValue(dealEl.getFirstChildElement("section1")));
				deal.setSection2(getValue(dealEl.getFirstChildElement("section2")));
				deal.setSection3(getValue(dealEl.getFirstChildElement("section3")));
				deal.setSaleStartAt(DateUtils.toDate(getValue(dealEl.getFirstChildElement("start_at")), "yyyy-MM-dd HH:mm:ss"));
				deal.setSaleEndAt(DateUtils.toDate(getValue(dealEl.getFirstChildElement("end_at")), "yyyy-MM-dd HH:mm:ss"));
				deal.setUseStartAt(getValue(dealEl.getFirstChildElement("coupon_start_at")));
				deal.setUseEndAt(getValue(dealEl.getFirstChildElement("coupon_end_at")));
				deal.setTitle(getValue(dealEl.getFirstChildElement("title")));
				deal.setWebLink(getValue(dealEl.getFirstChildElement("url")));
				deal.setMobileLink(getValue(dealEl.getFirstChildElement("mobile_url")));
				deal.setOriginalPrice(Integer.parseInt(getValue(dealEl.getFirstChildElement("original"))));
				deal.setSalesPrice(Integer.parseInt(getValue(dealEl.getFirstChildElement("price"))));
				deal.setDiscountRate(DiscountUtils.getRate(deal.getOriginalPrice(), deal.getSalesPrice()));
				deal.setMaxCount(Integer.parseInt(getValue(dealEl.getFirstChildElement("max_count"))));
				deal.setMinCount(Integer.parseInt(getValue(dealEl.getFirstChildElement("min_count"))));
				deal.setNowCount(Integer.parseInt(getValue(dealEl.getFirstChildElement("now_count"))));
				deal.setSalesStatus(getValue(dealEl.getFirstChildElement("today_use")));
				
				Element imageEl = dealEl.getFirstChildElement("images");
				deal.setImageUrl1(getValue(imageEl.getFirstChildElement("image")));
				deal.setImageUrl2(getImageUrl2(deal));
				
				Element shopsEl = dealEl.getFirstChildElement("shops");
				Elements shopsEls = shopsEl.getChildElements();
				for (int k = 0; k < shopsEls.size(); k++) {
					if (k == 0) {
						deal.setShopName(getValue(shopsEls.get(k).getFirstChildElement("shop_name")));
						deal.setShopAddress(getValue(shopsEls.get(k).getFirstChildElement("shop_address")));
						deal.setShopTelephone(getValue(shopsEls.get(k).getFirstChildElement("shop_tel")));
						
						String lat = getValue(shopsEls.get(k).getFirstChildElement("latitude"));
						String lon = getValue(shopsEls.get(k).getFirstChildElement("longitude"));
						
						if (lat != null && lat.length() > 5) {
							deal.setShopLatitude(lat);
						}
						if (lon != null && lon.length() > 5) {
							deal.setShopLongitude(lon);
						}
					}
				}
				
				deal.setImageUrl(getDefaultImageUrl(deal));
				deal.setAverageCount((int)(deal.getNowCount() / DateUtils.getTodayCount(deal.getSaleStartAt())));
				deal.setManageStatus(ManageStatus.S);
//				deal.setCategoryId(findCategoryId(getProviderCode(), deal));
				deal.setCategoryId(getCategoryId(deal));
				dealListDocument.add(deal);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}
		
		log.info(getProviderCode() + " deal size : " + dealListDocument.getDeals().size());
		
		return dealListDocument;
	}

	private String getDefaultImageUrl(Deal deal) {
		String imageUrl = deal.getImageUrl2();
		if (StringUtils.isBlank(imageUrl)) {
			imageUrl = deal.getImageUrl1();
		}
		return imageUrl;
	}

	private String getImageUrl2(Deal deal) {
		WemakeExtraDeal extraDeal = extraDeals.get(deal.getMetaId());
		if (extraDeal == null) {
			return null;
		}
		return extraDeals.get(deal.getMetaId()).getImageUrl();
	}

	private int getCategoryId(Deal deal) {
		WemakeExtraDeal extraDeal = extraDeals.get(deal.getMetaId());
		if (extraDeal == null) {
			return 100;
		}
		int categoryId = extraDeal.getCategoryId();
		int mainCategoryId = extraDeal.getMainCategoryId();
		if (categoryId == 0 && CategoryMapper.DEPTH_ONE_CATEGORY_FOOD == mainCategoryId) {
			return LocalCategoryUtils.getFoodCategoryId(deal.getShopAddress());
		} else if (categoryId == 0 && CategoryMapper.DEPTH_ONE_CATEGORY_BUTI == mainCategoryId) {
			return LocalCategoryUtils.getButiCategoryId(deal.getShopAddress());
		} else if (categoryId != 0) {
			return categoryId;
		}
		return 100;
	}
}
